/**
 * Created by htzhanglong on 2015/8/2.
 */
angular.module('starter.services', [])

    //本地存储
    .factory('Storage', function() {
        return {
            set: function(key, data) {
                return window.localStorage.setItem(key, window.JSON.stringify(data));
            },
            get: function(key) {

                return window.JSON.parse(window.localStorage.getItem(key));
            },
            remove: function(key) {
                return window.localStorage.removeItem(key);
            }
        };
    })
    //维修单列表
    .factory('RepairOrderList',function($rootScope,$resource,ENV){


        var ApiUrl = ENV.api+'RepairOrder_queryOrderForTechUser.json',
        // 用来存储维修单类别的数据结构，包含了下一页、是否有下一页等属性 ,topics[0] 待处理 ，topics[1] 维修中 topics[2] 已完成 topics[3] 转单  topics[4] 异常

        topics = {},
        status=0;
        var resource = $resource(ApiUrl, {}, {
            query: {
                method: 'get',
                params: {
                    status : '@status',
                    flag  : '@flag',
                    startPage:'@startPage'
                },
                timeout: 20000
            }
        });


        return {

            //获取第一页的数据
            getTopOrders:function(){

                var hasNextPage = true;   //是否有下一页

                resource.query({
                    status:status,
                    flag:0,
                    startPage:1
                }, function (r) {
                    if(r.success){
                        if (r.repairOrders.length < 10) {  //来判断是否有下一页数据
                            hasNextPage = false;
                        }
                        topics[status]={
                            hasNextPage:hasNextPage,
                            'nextPage': 2,
                            'data': r.result
                        }
                    }
                    //在这里请求完成以后  通知controller
                    $rootScope.$broadcast('OrderList.portalsUpdated');

                })
            } ,
            //返回我们保存的数据
            getOrders:function(){
                if(topics[status]===undefined){
                    return false
                }
              //  console.log(topics[catid].data);
                return topics[status].data;

            },
            getMoreOrders:function(){

                //为了解决一步加载的时候数据还没有加载完成  然后请求loadMore的时候  找不到数据
                if(topics[status]===undefined){
                    return false;
                }

                //获取以前的数据
                var hasNextPage=topics[status].hasNextPage;
                var nextPage=topics[status].nextPage;
                var moreTopicsData=topics[status].data;

                //console.log(moreTopicsData);

                resource.query({
                    status:status,
                    flag:0,
                    startPage:nextPage
                }, function (r) {
                    if(r.success){
                        nextPage++;
                        if (r.result.length < 20) {  //来判断是否有下一页数据
                            hasNextPage = false;
                        }
                        moreTopicsData=moreTopicsData.concat(r.result);
                        topics[status]={
                            hasNextPage:hasNextPage,
                            'nextPage': nextPage,
                            'data': moreTopicsData
                        }

                    }
                    //在这里请求完成以后  通知controller
                    $rootScope.$broadcast('PortalList.portalsUpdated');

                })
            },
            setOrderStatus:function(status){   //点击分类加载数据

                status=status;
                this.getTopTopics();

            },
            hasNextPage: function() {
                if (topics[status] === undefined) {
                    return false;
                }
                return topics[status].hasNextPage;
            }




        }


    })

    //技师待抢单列表
    .factory('TodoRepairOrderList',function($rootScope,$resource,ENV){

        var ApiUrl = ENV.api+'RepairOrder_queryAssignedOrder.json',
        // 用来存储维修单类别的数据结构，包含了下一页、是否有下一页等属性 ,topics[5] 待抢理

            topics = {},
            status=5;
        var resource = $resource(ApiUrl, {}, {
            query: {
                method: 'get',
                params: {

                },
                timeout: 20000
            }
        });


        return {

            //获取第一页的数据
            getTopOrders:function(){

                var hasNextPage = true;   //是否有下一页

                resource.query({

                }, function (r) {
                    if(r.success){
                        console.log(r);
                        if (r.repairOrders.length < 10) {  //来判断是否有下一页数据
                            hasNextPage = false;
                        }
                        topics[status]={
                            hasNextPage:hasNextPage,
                            'nextPage': 2,
                            'data': r.repairOrders
                        }
                    }
                    //在这里请求完成以后  通知controller
                    $rootScope.$broadcast('TodoOrderList.portalsUpdated');

                })
            } ,
            //返回我们保存的数据
            getOrders:function(){
                if(topics[status]===undefined){
                    return false
                }
                //  console.log(topics[catid].data);
                return topics[status].data;

            },
            getMoreOrders:function(){

                //为了解决一步加载的时候数据还没有加载完成  然后请求loadMore的时候  找不到数据
                if(topics[status]===undefined){
                    return false;
                }

                //获取以前的数据
                var hasNextPage=topics[status].hasNextPage;
                var nextPage=topics[status].nextPage;
                var moreTopicsData=topics[status].data;

                //console.log(moreTopicsData);

                resource.query({
                    status:status,
                    flag:0,
                    startPage:nextPage
                }, function (r) {
                    if(r.success){
                        nextPage++;
                        if (r.result.length < 20) {  //来判断是否有下一页数据
                            hasNextPage = false;
                        }
                        moreTopicsData=moreTopicsData.concat(r.result);
                        topics[status]={
                            hasNextPage:hasNextPage,
                            'nextPage': nextPage,
                            'data': moreTopicsData
                        }
                    }
                    //在这里请求完成以后  通知controller
                    $rootScope.$broadcast('TodoOrderList.portalsUpdated');

                })
            },
            // setOrderStatus:function(status){   //点击分类加载数据
            //
            //     status=status;
            //     this.getTopTopics();
            //
            // },
            hasNextPage: function() {
                if (topics[status] === undefined) {
                    return false;
                }
                return topics[status].hasNextPage;
            }




        }


    })

    //维修单详情
    .factory('RepairOrderContent', function($resource, $rootScope,ENV) {
        var ApiUrl = ENV.api+"repairOrder_queryOrderInfo.json",
            order = {},
            grabResponse={};
        var resource = $resource(ApiUrl, {}, {
            query: {
                method: 'get',
                params: {
                    repairOrderId: '@repairOrderId'
                },
                timeout: 20000
            }
        });
        //技师抢单
        var ApiUrl1 = ENV.api+"RepairOrder_robOrder.json";

        var resource1 = $resource(ApiUrl1, {}, {
            query: {
                method: 'get',
                params: {
                    RepairOrderId: '@repairOrderId'
                },
                timeout: 20000
            }
        });



        return {

            get: function(aid) {
                // console.log(aid);
                return resource.query({
                    repairOrderId: aid
                }, function(response) {
                    // console.log(response);
                    order = response.repairOrder;
                    $rootScope.$broadcast('RepairOrder.contentUpdated');
                });

            },
            getArticle: function() {
                return order;
            },

            grab:function (id) {
                return resource1.query({
                    RepairOrderId: id
                },function(response){
                    console.log("response:"+response);
                    grabResponse=response;
                    $rootScope.$broadcast('RepairOrder.grabSuccess');
                });

            },
            getGrabResult:function(){
                return grabResponse;
            }


        };


    })

    //技师任务列表
    .factory('TaskList', function($resource, $rootScope,ENV) {
        var ApiUrl = ENV.api+'RepairOrder_queryOrderForTechUser.json',
        // 用来存储维修单类别的数据结构，包含了下一页、是否有下一页等属性 ,topics[0] 待处理 ，topics[1] 维修中 topics[2] 已完成 topics[3] 转单  topics[4] 异常
            topics = {},
            status = 0,
            flag=0,
            listNum=0;
        var resource = $resource(ApiUrl, {}, {

            query: {
                method: 'get',
                params: {
                    status: '@status',
                    flag: '@flag',
                    startPage:'@startPage'
                },
                timeout: 20000
            }
        });


        return {
            getTopList: function() {

                // console.log("currentTab: " + currentTab);
                var hasNextPage = true;   //是否有下一页

                resource.query({
                    status: status,
                    startPage: 1,
                    flag:flag
                }, function(r) {
                    if(r.success){
                        listNum=r.orderNum;
                        if (r.repairList.length < 10) {
                            hasNextPage = false;
                        }
                        topics[status] = {
                            'nextPage': 2,
                            'hasNextPage': hasNextPage,
                            'data': r.repairList
                        };
                    }
                    $rootScope.$broadcast('TaskList.listUpdated');

                });
            },
            getList: function() {

                if (topics[status] === undefined) {
                    return false;
                }
                return topics[status].data;
            },
            getListNum: function() {
              return listNum;
            },
            getCurrentStatus: function() {
                return status;
            },

            setOrderStatus:function(newStatus,newFlag){   //点击分类加载数据
                status=newStatus;
                flag=newFlag;
                this.getTopList();
            },
            getMoreList: function() {
                var nextPage = topics[status].nextPage;
                var hasNextPage = topics[status].hasNextPage;
                var portalsData = topics[status].data;

                //console.log(nextPage)

                resource.query({
                    status: status,
                    startPage: nextPage,
                    flag:flag
                }, function(r) {
                    // console.log(r);
                    if(r.success){
                        nextPage++;
                        if (r.repairList.length < 20) {
                            hasNextPage = false;
                        }

                        //    console.log(r.result);

                        portalsData = portalsData.concat(r.result);
                        topics[status] = {
                            'nextPage': nextPage,
                            'hasNextPage': hasNextPage,
                            'data': portalsData
                        };
                    }

                    $rootScope.$broadcast('TaskList.listUpdated');

                });
            },
            hasNextPage: function() {
                if (topics[status] === undefined) {
                    return false;
                }
                return topics[status].hasNextPage;
            }


        };


    })


    //帖子详情
    .factory('ThreadContentFactory', function($resource, $rootScope,ENV) {
        var APIUrl = ENV.api ,
            topic;

        var resource = $resource(APIUrl, {}, {
            query: {
                method: 'get',
                params: {
                    a:'getThreadContent',
                    aid: '@tid'
                },
                timeout: 20000
            }
        });


        return {

            get: function(tid) {
                return resource.query({
                    tid: tid
                }, function(response) {
                    topic = response.result;

                    $rootScope.$broadcast('ThreadContent.threadUpdated');
                });

            },
            getThread: function() {
                return topic;
            },
            saveReply: function(topicId, replyData) {
                //发表帖子
            }


        };

    })

    //用户登录
    .factory('User', function($resource, $rootScope,ENV,Storage,$http,Toast) {
        var APIUrl = ENV.api ,
            user;
        var storageKey='user';
        var resource = $resource(APIUrl+'user_technician_login.json');

        return {
            login: function(username,password) {

                var formData={loginName:username,password:password};

                // return resource.save({
                //     loginName: username,
                //     password: password
                // }, function(response) {
                //     console.log("登录response"+response);
                //     user=response;
                //     $rootScope.$broadcast('User.loginUpdated');
                // });

              $http({
                method: 'POST',
                url: ENV.api+'user_technician_login.json',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: formData,
                transformRequest: function (obj) {               //将对象进行参数序列化
                  console.info(obj);
                  var str = [];
                  for (var p in obj) {
                    str.push(p + "=" + obj[p]);
                  }
                  var serialString = str.join("&");
                  console.info(serialString);
                  return serialString;
                }

              }).then(function (response) {
                console.log("登陆response"+response.currentUser);
                user=response.data;
                $rootScope.$broadcast('User.loginUpdated');
              }, function (err) {
                console.log("=======登录失败"+err);
                if(err.status==0){
                  Toast.show("网络错误！");
                }

              });





            },
            logout: function() {
                user = {};
                Storage.remove(storageKey);
                Storage.remove("sessionId");

            },
            getCurrentUser: function(){
                return user;
            }


        };

    })

    // .factory('authInterceptor', function($rootScope,Storage){
    //     return {
    //         request: function(config){
    //             config.headers = config.headers || {};
    //             console.log("请求头部："+config.headers);
    //             if(Storage.get("sessionId")){
    //                 config.headers.Cookie = 'JSESSIONID=' +Storage.get("sessionId");
    //             }
    //             return config;
    //         },
    //         responseError: function(response){
    //             // ...
    //         }
    //     };
    // })

    //检测用户的登录状态
    .factory('CheckLogin', function($resource, $rootScope,ENV) {
        var APIUrl = ENV.api ,
            checkResult={};
        // var storageKey='user';
        // var resource = $resource(APIUrl+'technician_checkLogin.json');
        var resource = $resource(APIUrl+'user_technician_checkLogin.json', {}, {
            query: {
                method: 'get',
                params: {
                    sessionId : '@sessionId'
                },
                timeout: 30000
            }
        });

        return {
            checkLogin: function(sessionId) {
                return resource.query({
                    sessionId: sessionId
                }, function(response) {
                    console.log("检测登陆结果："+JSON.stringify(response));
                    checkResult=response;
                    $rootScope.$broadcast('User.CheckLoginUpdated');
                });
            },
            getResult: function(){
                return checkResult;
            }


        };

    })
    //弹窗提示
    .factory('Toast', function($resource, $rootScope,$ionicLoading) {
        return {
            show: function(msg) {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: msg,
                    duration: 1500
                });
            }
        };

    })
    .factory('FileUtil',function(ENV, $cordovaFileTransfer,$http,$resource, $ionicLoading,$log, $q, Toast,$rootScope){

    //服务器的上传接口
    var serveURL =ENV.api+"RepairOrder_uploadNodePic.json";
    var imgSrc=[];
    return{
      //文件上传
      /*@fileURI 文件路径
       * */
      upload:function(fileURI){
        /*The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request. Both HTTP and HTTPS protocols are supported. Optional parameters can be specified by passing a FileUploadOptions object to the upload() method. On successful upload, a FileUploadResult object is passed to the success callback. If an error occurs, a FileTransferError object is passed to the error callback.
         * 也就是说FileTransfer 提供了一种方式去上传文件,HTTP multi-part POST.我们平常在前端使用form表单当指定enctype="multipart/form-data"就是这种规范。
         * 如下例子1：
         * <form action="file_upload.json" method="post" enctype="multipart/form-data">
         * <input type="hide" name="isApp" value="true">
         <input type="file" name="uploadFile" multiple="multiple">
         <input type="submit" value="提交">
         </form>
         参考：http://cordova.apache.org/docs/en/3.1.0/cordova_file_file.md.html#FileTransfer
         这里需要特别注意：需要引入cordova支持，才有FileTransfer() FileUploadOptions()这些类。
         因为我这里使用的是ngCordova(参考大神的文章：http://www.haomou.net/2015/01/05/2015_ionic_ngCordova/)，简单来说就是又封装了一层，方便移动端使用。
         ngCordova的插件使用参考：http://ngcordova.com/docs/plugins/fileTransfer/（这个是file-transfer），如果你去看源码你会发现其实就是调用的cordova的FileTransfer
         * */
        /*不使用FileUploadOption的原因是ngCordova里面把这个配置项类给去了，使用了一个{}对象来实现，没有区别，要使用new FileUploadOption()需要引入cordova的，因为我这里没有就是用的官方给出的例子*/
        //对于options 官方给出的解释是Optional parameters，并没有过多的解释，在使用的时候很不明白，对于我这样的小白来说简直就是一个巨坑，参考了诸多大神写的代码和查询了无数的资料以后现在我来说一下我的理解，在这里感谢诸位大神的分享：
        //列出大神的文章地址以便参考：http://my.oschina.net/u/561475/blog/104308
        //                       http://my.oschina.net/twinkling/blog/474297
        var options = {};
        options.fileKey = "files";//用于设置参数，对应form表单里控件的name属性，这是关键，废了一天时间，完全是因为这里，这里的参数名字，和表单提交的form对应
        //文件名字就好
        options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);


        //如果是图片格式，就用image/jpeg，其他文件格式上官网查API

        options.mimeType = "multipart/form-data";

        //options.mimeType = "multipart/form-data";//这两个参数修改了，后台就跟普通表单页面post上传一样 enctype="multipart/form-data"


        //这里我把isApp 用params的方式，也就是通过？key&value的方式追加在url后面，成功上传文件
        //如果我不用也能上传成功，但是后台提示的信息显示保存到了别的位置，我觉得应该是这样的，后台通过isApp来表示上传的文件保存到哪里，但是我不理解的是
        //form 表单设置enctype="multipart/form-data"时候对于非file标识的input是如何传递给后台的，我这里采取的方式是追加在url，居然也可以接受，这一块还需要研究，主要要搞懂后台和协议的细节
        var params = new Object();

        // params.isApp = true;
        // params.articleId =924;

        options.params = params;

        var deferred=$q.defer();
        var promise =deferred.promise;
        document.addEventListener('deviceready', function () {

          $cordovaFileTransfer.upload(serveURL, fileURI, options)
            .then(function(result) {

              //这里的result 就是返回http协议的response的data，没有header 和state那些

              //返回请求的数据，也有可能是失败的信息，虽然网络请求成功了，但是服务器因为一些原因没有做客户端想的事情，告诉客户端错误信息
             if(JSON.parse(result.response).success){
               imgSrc.push(JSON.parse(result.response).picUrl);
               $rootScope.$broadcast('RepairOrder.UploadSuccess');
             }
            else{
                $ionicLoading.hide();
                Toast.show("系统出错，提交失败");
            }
            }, function(err) {
              // Error
              $ionicLoading.hide();
              Toast.show('网络错误');

            }, function (progress) {
              // constant progress updates
            });

        }, false);

        return promise;
      },
      download:function(serveURL,fileURI,options){

      },
      getImgSrc:function () {
        return  imgSrc;
      },
      setImgSrc:function () {
        imgSrc=[];
      }
    }

  })

    .factory('SubmitNodeReport',function(ENV,$resource,Toast,$rootScope,$ionicLoading) {
          var ApiUrl = ENV.api + "RepairOrder_uploadRepairStage.json";
          var resource = $resource(ApiUrl, {}, {
            query: {
              method: 'get',
              params: {
                orderNum: '@orderNum',
                repairStageContent: '@repairStageContent',
                imgSrcArray: '@imgSrcArray'
              },
              timeout: 20000
            }
          });


          return {

            submit: function (orderNum, repairStageContent, imgSrcArray) {
              return resource.query({
                orderNum: orderNum,
                repairStageContent: repairStageContent,
                imgSrcArray: imgSrcArray
              }, function (response) {
                $ionicLoading.hide();
                $rootScope.$broadcast('RepairOrder.NodeReportEd');
                Toast.show(response.msg);
              });

            }

          }
    })

     //载入背景幕
    .factory('Load', function($resource, $rootScope,$ionicLoading) {
    return {
      loading: function(msg) {
          //显示载入指示器
          $ionicLoading.show({
            template: msg
          });
          // //延时2000ms来模拟载入的耗时行为
          // $timeout(function(){
          //   for(var i=0;i<10;i++,idx++) $scope.items.unshift("item " + idx);
          //   //隐藏载入指示器
          //   $ionicLoading.hide();
          // },2000);
      }
    };

  })

     //提交转单申请   和   提交结束申请
    .factory('TurnTransfor',function($resource,ENV,Toast,$rootScope,$timeout){
        var ApiUrl=ENV.api+'RepairOrder_turnOrder.json';
        var ApiUrl1=ENV.api+"RepairOrder_finishRepair.json";  //结束订单
        var resource = $resource(ApiUrl, {}, {
          query: {
            method: 'get',
            params: {
              roId : '@repairOrderId',
              repairStageContent:'@repairStageContent'
            },
            timeout: 20000
          }
        });
        var resource1= $resource(ApiUrl1, {}, {   //结束
          query: {
            method: 'get',
            params: {
              roId : '@repairOrderId',
            },
            timeout: 20000
          }
        });





        return {

          putTransfor: function (aid,repairStageContent) {
            // console.log(aid);
            return resource.query({
              roId: aid,
              repairStageContent:repairStageContent
            }, function (response) {

              Toast.show(response.msg);
              if(response.success){
                $timeout(function(){
                  $rootScope.$broadcast('RepairOrder.PutTurnEd');
                },1500)
              }
            });

          },
          finishOrder: function (aid) {
            // console.log(aid);
            return resource1.query({
              roId: aid,
            }, function (response) {
              Toast.show(response.msg);
              if(response.success){
                $timeout(function(){
                  $rootScope.$broadcast('RepairOrder.Finished');
                },1500)
              }
            });

          },




        }

  })
     //提交上报申请
    .factory('TurnException',function($resource,ENV,Toast,$rootScope,$timeout){
        var ApiUrl=ENV.api+'RepairOrder_turnException.json';
        var resource = $resource(ApiUrl, {}, {
          query: {
            method: 'get',
            params: {
              roId : '@repairOrderId',
              repairStageContent:'@repairStageContent'
            },
            timeout: 20000
          }
        });

      return {

        putException: function (aid,repairStageContent) {
          // console.log(aid);
          return resource.query({
            roId: aid,
            repairStageContent:repairStageContent
          }, function (response) {
            Toast.show(response.msg);
            if(response.success){
              $timeout(function(){
                $rootScope.$broadcast('RepairOrder.ExceptionEd');
              },1500)
            }
          });

        },
    }

  })

     //查询订单的维修节点
    .factory('RepairNode',function($resource,ENV,Toast,$rootScope){
        var ApiUrl=ENV.api+'repairOrder_queryRepairStage.json';
        var repairNodes={};
        var resource = $resource(ApiUrl, {}, {
          query: {
            method: 'get',
            params: {
              orderNum : '@orderNum'
            },
            timeout: 20000
          }
        });

        return {

          getRepairNodes: function (orderNum) {
            // console.log(aid);
            return resource.query({
              orderNum: orderNum
            }, function (response) {
              repairNodes=response.repairOrders;
              // Toast.show(response.msg);
              $rootScope.$broadcast('RepairOrder.nodeSuccessEd');
            });

          },
          getNodes:function(){
            return repairNodes;
          }
        }

    })
     //技师修改个人信息
    .factory('modifyInfo',function($resource,ENV,Toast,$rootScope,Storage){
        var ApiUrl=ENV.api+'user_techUserUpdate.json';
        var resource = $resource(ApiUrl, {}, {
          query: {
            method: 'get',
            params: {
              goodAtWork:'@goodAtWork',
              name:'@name',
              tel:'@tel'


            },
            timeout: 20000
          }
        });

        return {

          modifyJobType: function (goodAtWork) {
            // console.log(aid);
            return resource.query({
              goodAtWork:goodAtWork
            }, function (response) {
              Toast.show(response.msg);
              if(response.success){
                var newUser=Storage.get('user');
                newUser.goodAtWork=goodAtWork;
                Storage.set("user",newUser);

              }
              $rootScope.$broadcast('UserInfo.modifyJobType');
            });

          },
          modifyName:function(name){
            return resource.query({
              name:name
            }, function (response) {
              Toast.show(response.msg);
              if(response.success){
                var newUser=Storage.get('user');
                newUser.userName=name;
                Storage.set("user",newUser);

              }
              $rootScope.$broadcast('UserInfo.modifyJobType');
            });
          },
          modifuGender:function(gender){
            return resource.query({
              gender:gender
            }, function (response) {
              Toast.show(response.msg);
              if(response.success){
                var newUser=Storage.get('user');
                newUser.gender=gender;
                Storage.set("user",newUser);

              }
              $rootScope.$broadcast('UserInfo.modifyJobType');
            });
          }
        }

  })
     //弹出webview
    .factory('webview',function(){
      return {
        openWeb: function (param) {
          cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?do=search&id=' + param, '_blank', {
            statusbar: {
              color: '#0000FF'
            },
            toolbar: {
              height: 44,
              color: '#444444'
            },
            title: {
              color: '#ffffff',
              staticText: '详情',
              showPageTitle: false
            },
            backButton: {
              image: 'back',
              imagePressed: 'back_pressed',
              align: 'left',
              event: 'backPressed'
            },
            customButtons: [
              {
                image: 'share',
                imagePressed: 'share_pressed',
                align: 'right',
                event: 'sharePressed'
              }
            ],
            menu: {
              image: 'menu',
              imagePressed: 'menu_pressed',
              title: 'Test',
              cancel: 'Cancel',
              align: 'right',
              items: [
                {
                  event: 'helloPressed',
                  label: 'Hello World!'
                },
                {
                  event: 'testPressed',
                  label: 'Test!'
                }
              ]
            },
            backButtonCanClose: true
          }).addEventListener('backPressed', function (e) {
            // alert('back pressed');
          }).addEventListener('helloPressed', function (e) {
            alert('hello pressed');
          }).addEventListener('sharePressed', function (e) {
            alert(e.url);
          }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
            console.error(e.message);
          }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
            console.log(e.message);
          });
        }
      }
  })

     //点击开始维修
    .factory('startRepair',function($resource,ENV,Toast,$rootScope,Storage,$timeout){
        var ApiUrl=ENV.api+'RepairOrder_startRepair.json';
        var resource = $resource(ApiUrl, {}, {
          query: {
            method: 'get',
            params: {
              RepairOrderId :'@RepairOrderId',
            },
            timeout: 20000
          }
        });

    return {

      start: function (id) {
        // console.log(aid);
        return resource.query({
          RepairOrderId: id
        }, function (response) {
          Toast.show(response.msg);
          if (response.success) {
            $timeout(function(){
              $rootScope.$broadcast('StartRepair.Started');
            },1000)

          }



        });

      }
    }

  })
     //修改密码
    .factory('modifyPassword',function($resource,ENV,Toast,$rootScope,Storage){
        var ApiUrl=ENV.api+'user_techUserUpdatePassword.json';
        var resource = $resource(ApiUrl);


        return {

          sendModify: function (oldPassword,newPassword) {
            // console.log(aid);
            return resource.get({
              oldPassword:oldPassword,
              newPassword:newPassword
            }, function (response) {
              Toast.show(response.msg);
              if (response.success) {
                $timeout(function(){
                  $rootScope.$broadcast('modifyPassword.Success');
                },1500)

              }
            });

      }
    }

  })
     //查询待抢单数量
    .factory('queryNum',function($resource,ENV,Toast,$rootScope,Storage){
        var ApiUrl=ENV.api+'RepairOrder_queryAssignedOrderCount.json';
        var resource = $resource(ApiUrl);
        var todoNum=0;


        return {

          query: function () {
            // console.log(aid);
            return resource.get({

            }, function (response) {
              if (response.success) {
                  todoNum=response.count;
                  $rootScope.$broadcast('queryNum.Success');
              }
            });
          },
          getTodoNum:function(){
            return todoNum;
          }
        }

  })

    //获取收款项产品列表
    .factory('productList', function($resource, $rootScope,ENV) {
        var ApiUrl = ENV.api+'buildingOffer_queryChargeProduct.json',
        // 用来存储维修单类别的数据结构，包含了下一页、是否有下一页等属性 ,topics[0] 待处理 ，topics[1] 维修中 topics[2] 已完成 topics[3] 转单  topics[4] 异常
            productOne = {},
            productTwo={},
            productThree={}

        var resource = $resource(ApiUrl, {}, {
            query: {
                method: 'get',
                params: {
                    chargeProductId: '@chargeProductId'
                },
                timeout: 20000
            }
        });


        return {
            setProductOne: function () {
                resource.query({
                    chargeProductId: 0   //获取一级产品
                }, function (r) {
                    if (r.success) {
                        productOne = r.chargeProducts;
                    }
                    $rootScope.$broadcast('productList.listOneUpdated');

                });
            },

            setProductTwo: function (chargeProductId) {
                resource.query({
                    chargeProductId: chargeProductId   //获取二级产品
                }, function (r) {
                    if (r.success) {
                        productTwo = r.chargeProducts;
                    }
                    $rootScope.$broadcast('productList.listTwoUpdated');

                });
            },
            setProductThree: function (chargeProductId) {
                resource.query({
                    chargeProductId: chargeProductId   //获取二级产品
                }, function (r) {
                    if (r.success) {
                        productThree = r.chargeProducts;
                    }
                    $rootScope.$broadcast('productList.listThreeUpdated');

                });
            },
            getProductOne: function () {
               return  productOne;
            },
            getProductTwo: function () {
                return  productTwo;
            },
            getProductThree: function () {
                return  productThree;
            }

        }

    })

//获取收款项产品列表
    .factory('placeOrder', function($resource, $rootScope,ENV) {
        var ApiUrl = ENV.api+'buildingOffer_queryChargeProductInfoByIds.json',
        // 用来存储维修单类别的数据结构，包含了下一页、是否有下一页等属性 ,topics[0] 待处理 ，topics[1] 维修中 topics[2] 已完成 topics[3] 转单  topics[4] 异常
            productInfoList = {}


        var resource = $resource(ApiUrl, {}, {
            query: {
                method: 'get',
                params: {
                    chargeProductIds: '@chargeProductId'
                },
                timeout: 20000
            }
        });


        return {
            setProductInfoList: function (productIds) {
                resource.query({
                    chargeProductId: productIds   //获取一级产品
                }, function (r) {
                    if (r.success) {
                        productInfoList = r.chargeProducts;
                    }
                    $rootScope.$broadcast('productInfoList.listUpdated');

                });
            },


            getProductInfo: function () {
                return  productInfoList;
            }

        }

    })
















